﻿using System;
using System.Collections.Specialized;
using System.Text;
using System.Web;
using WebDotNet.Extensions;
using WebDotNet.Samples.TodoList.App.Entities;
using WebDotNet.Samples.TodoList.App.Model;

namespace WebDotNet.Samples.TodoList.App.Handlers
{
	public class Update
	{
		public StringBuilder Post(HttpContextBase httpContextBase)
		{
			Todo todo = getFromForm(httpContextBase.Request.Form);

			XmlRepository<Todo> repository = new XmlRepository<Todo>();
			repository
				.RemoveAll(t => t.Id == todo.Id)
				.Add(todo)
				.Save();

			if (httpContextBase.IsAjaxRequest())
			{
				return null;
			}
			else
			{
				httpContextBase.Response.Redirect("~/#t" + todo.Id.ToString(), true);
				return null;
			}
		}

		private Todo getFromForm(NameValueCollection nameValueCollection)
		{
			Todo todo = new Todo()
			{
				Id = Guid.Parse(nameValueCollection["Id"]),
				Title = nameValueCollection["Title"],
				IsDone = bool.Parse(nameValueCollection["IsDone"]),
				CreatedOn = DateTime.Parse(nameValueCollection["CreatedOn"])
			};

			return todo;
		}
	}
}
